import React, {forwardRef, useEffect, useImperativeHandle, useState} from "react";
import { Button, Space, Table, TableColumnType, message } from "antd";
import { activityTypes  } from "@/constants/types";
import { calculateTableWidth } from "@/utils/util";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import { useComponentDidMount } from "@/hooks";
import { fetchActivityList, updateActivity, activityAddMember, activityStartActivity } from "../services";
import ActivityUpdate from "../modals/ActivityUpdate";
import { useRequest } from "ahooks";
import ActivityDetail from "../modals/ActivityDetail";
import ViewActivityCode from "../modals/ViewActivityCode";
import AddActivityCode from "../modals/AddActivityCode";
import dayjs from "dayjs";


interface tabProps {
  activeKey: string;
  tabKey: string,
  refreshNum: Function,
  tabChangeShouldUpdateTab: string[]
}

const ActivityManageTable = forwardRef(({activeKey, tabKey, refreshNum, tabChangeShouldUpdateTab}: tabProps, ref) => {
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: 10,
    total: 0
  });
    // 编辑活动
    const [visible, setVisible] = useState(false);
    const [currentRow, setCurrentRow] = useState<activityTypes | null>(null);
    const {loading: updateLoading, runAsync: updateApi} = useRequest(updateActivity, {manual: true});
    // 活动详情
    const [activityViewVisible, setActivityViewVisible] = useState(false);
    // 创建活动码
    const [codeCreateVisible, setCodeCreateVisible] = useState(false);
    const {loading: codeCreateLoading, runAsync: codeCreateApi} = useRequest(activityAddMember, {manual: true});
    // 查看活动码
    const [codeViewVisible, setCodeViewVisible] = useState(false);


  const search = async (params:{pageNum: number; pageSize: number} = {
    pageNum: 1,
    pageSize: 10
  }) => {
    const statusMaps: any = {
      all: undefined,
      todo: '0',
      doing: '1',
      done: '2'
    }
    const res = await fetchActivityList({
      ...params,
      status: statusMaps?.[tabKey]
    });
    setDataSource(res?.data || []);
    setPagination({
      ...params,
      total: res?.total
    });
  }


  const refreshTable = () => {
    if (activeKey !== tabKey) {
      return ;
    }
    search({
      pageNum: 1,
      pageSize: 10
    });
  }

  // 编辑活动
  const activityUpdateProps = {
    title: '编辑活动',
    visible,
    currentRow,
    loading: updateLoading,
    onCancel: () => {
      setVisible(false);
    },
    onSubmit: async (params: activityTypes) => {
      const res = await updateApi(params);
      if (res.code === '0') {
        message.success('操作成功');
        activityUpdateProps.onCancel();
        refreshTable();
      }
    }
  }
  // 查看活动详情
  const activityViewProps = {
    title: '活动详情',
    visible: activityViewVisible,
    currentRow,
    onCancel: () => {
      setCurrentRow(null);
      setActivityViewVisible(false);
    }
  }
  // 创建活动码
  const codeCreateProps = {
    title:'创建渠道码',
    loading: codeCreateLoading,
    visible: codeCreateVisible,
    currentRow,
    onCancel: () => {
      setCurrentRow(null);
      setCodeCreateVisible(false);
    },
    onSubmit: async (params:  {
      activityId: string;
      mobile: string;
    }) => {
      const res = await codeCreateApi(params);
      if (res?.code === '0') {
        codeCreateProps.onCancel();
        refreshTable();
      }
    }
  }
  // 查看活动码
  const codeViewProps = {
    visible: codeViewVisible,
    currentRow,
    onCancel: () => {
      setCurrentRow(null);
      setCodeViewVisible(false);
    }
  }

  const handleEdit = (record: activityTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }
  const handleActivityView = (record: activityTypes) => {
    setCurrentRow(record);
    setActivityViewVisible(true);
  }
  const handleCodeView = (record: activityTypes) => {
    setCurrentRow(record);
    setCodeViewVisible(true);
  }
  const handleCodeCreate = (record: activityTypes) => {
    setCurrentRow(record);
    setCodeCreateVisible(true);
  }
  const handleAble = (record: activityTypes) => {
    activityStartActivity({id: record?.id}).then(
      res => {
        if (res?.code === '0') {
          message.success('开启成功');
          refreshTable();
        }
      }
    )
  }

  const fieldColumns: TableColumnType<activityTypes> [] = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (_, record, index) => <span>{index + 1}</span>,
      width: 80
    },
    {
      title: '活动状态',
      dataIndex: 'status',
      render: (_, record) => <XlTableDictColumn type="activityStatus" value={record?.status} />,
      width: 100
    },
    {
      title: '活动名称',
      dataIndex: 'name',
      width: 150
    },
    {
      title: '活动类型',
      dataIndex: 'type',
      width: 120,
      render: (_, record) => <XlTableDictColumn type="activityType" value={record?.type} />
    },
    {
      title: '活动开始时间',
      dataIndex: 'startTime',
      width: 170
    },
    {
      title: '活动结束时间',
      dataIndex: 'endTime',
      width: 170
    },
    {
      title: '活动奖励优惠券',
      ellipsis: true,
      dataIndex: 'activityRewards',
      width: 150
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      width: 110
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 170
    },
    {
      title: '操作',
      dataIndex: 'options',
      width: 490,
      fixed: 'right',
      render: (_, record) => {
        const now = new Date();
        const showAbleBtn = record?.status === '0' && (dayjs(now).isAfter(dayjs(record?.startTime)) && dayjs(now).isBefore(dayjs(record?.endTime)))
        return (
          <Space>
              <Button type="link" onClick={() => handleActivityView(record)}>活动详情</Button>
              {(record?.status === '1' || record?.status === '0') && <Button type="link" onClick={() => handleCodeView(record)}>查看活动码</Button>}
              {(record?.status === '1' || record?.status === '0') && <Button type="link" onClick={() => handleCodeCreate(record)}>创建活动码</Button>}
              {record?.status === '0' && <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>}
              {showAbleBtn && <Button type="link" onClick={() => handleAble(record)}>启用</Button>}
          </Space>
        );
      }
    },
  ];
 

  const getColumns = () => {
    return fieldColumns;
  }




  useImperativeHandle(ref, () => ({
    refreshTable
  }));


  useEffect(() => {
    if (tabKey === activeKey && tabChangeShouldUpdateTab.includes(activeKey)) {
      search({
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize
      });
    }
  }, [tabKey, activeKey]);

  useComponentDidMount(() => {
    if (!tabChangeShouldUpdateTab.includes(activeKey)) {
      search({
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize
      });
    }
  })


  return (
    <>
      <Table
        className="mt20"
         bordered
         rowKey="id"
         dataSource={dataSource}
         columns={getColumns()}
         scroll={{x: calculateTableWidth(getColumns())}}
         pagination= {{
          showTotal: (total: number) => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            search({pageNum, pageSize});
          }
         }}
      />
      {visible && <ActivityUpdate {...activityUpdateProps} />}
      {activityViewVisible && <ActivityDetail {...activityViewProps} />}
      {codeCreateVisible && <AddActivityCode {...codeCreateProps} />}
      {codeViewVisible && <ViewActivityCode {...codeViewProps} />}
    </>
  );
});


export default ActivityManageTable;